<?php
namespace app\admin\controller;
use app\admin\common\Base;
use think\Db;
use think\facade\Request;
use think\Exception;
use app\admin\model\Merchant as MerchantModel;
use app\admin\model\MerchantService as MerchantServiceModel;
use app\admin\model\MerchantOverarea as MerchantOverareaModel;

/**
* 商家控制器
*/
class Merchant extends Base{

    use \app\admin\traits\BaseFn;

    protected $model = null;

    public function initialize(){
        parent::initialize();
        $this->model = new MerchantModel();
    }

    /**
     * 列表
     */
    public function index(){
        if(Request::isAjax()){

            list($where,$sort) = $this->buildQuery();

            $where[] = ['is_del', '=', 0];  //非删除
            $list = $this->model
                ->where($where)
                ->order('id desc')
                ->paginate(Request::param('pageSize'));

            $list = $list->toArray();
            foreach($list['data'] as &$row){
                $row['contact_phone'] = (array)(da_jdecode($row['contact_phone'], true));
            }
            unset($row);

            $data = [
                "total"=>$list['total'],
                'rows'=>$list['data'],
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $post = Request::param();
                $where = [];

                if( !empty($post['name']) ){
                    //判断商家名是否存在
                    $where[] = ['name','eq',$post['name']];
                    $count = $this->model->where($where)->count();
                    if($count>0){
                        $code = 10002;
                        throw new Exception('商家名已存在');
                    }
                }

                //多个电话
                $post['phone'] = array_diff($post['phone'], ['']);
                array_splice($post['phone'],5);  //最多只保留5个电话
                $post['contact_phone'] = da_jencode( $post['phone']);
                unset($post['phone']);

                foreach ($post as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        //时间自动转为时间戳
                        $post[$key] = strtotime($value);
                    }
                }
                $post['add_time'] = time();
                $insert = $this->model->allowField(true)->save($post);//过滤数据库字段写入


                if($insert){
                    $msg = "添加成功";

                    //隐藏表单--服务范围
                    $srv_area = $this->request->post('srv_area/a', []);
                    $mch_id = $this->model->id;
                    if(count($srv_area)){
                        if( mb_substr($post['mch_province'],-1,null, 'utf-8')=='市' ) $post['mch_city'] = $post['mch_province'];  //直辖市
                        $ms = new MerchantOverareaModel();
                        $ms->save([
                            'mch_id' => $mch_id,
                            'srv_province' => $post['mch_province'],
                            'srv_city' => $post['mch_city'],
                            'srv_areas' => da_jencode($srv_area),
                        ]);
                    }



                }else{
                    $code = 10001;
                    throw new Exception('添加失败');
                }

            }catch (Exception $e){
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        return $this->fetch();
    }


    /**
     * 编辑
     */
    public function edit(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $where = [
                    'id'=>Request::param('id'),
                ];
                $update = Request::except('id');

                if( !empty($update['name']) ) {
                    //判断用户名是否存在
                    $map = [];
                    $map[] = ['name', 'eq', $update['name']];
                    $map[] = ['id', 'neq', $where['id']];
                    $count = $this->model->where($map)->count();
                    if ($count > 0) {
                        $code = 10002;
                        throw new Exception('商家名已存在');
                    }
                }

                //多个电话 ,数组求差集
                $update['phone'] = array_diff($update['phone'], ['']);
                array_splice($update['phone'],5);  //最多只保留5个电话
                $update['contact_phone'] = da_jencode( $update['phone']);
                unset($update['phone']);

                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        //时间自动转为时间戳
                        $update[$key] = strtotime($value);
                    }
                }

                $this->model->save($update,$where);
                $msg = "保存成功";

            }catch (Exception $e){
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        $where = Request::param();
        $data = $this->model->where($where)->find();
        $data['phone'] = (array)( da_jdecode($data['contact_phone'],true) );
        $data['phone'] = array_diff($data['phone'], ['']);  //去除空元素
        $this->assign('data',$data);
        return $this->fetch();
    }


    //删除
    public function softDel(){
        $code = 0;
        $msg = 'success';
        $data = null;
        try{
            if(Request::isAjax()){
                $ids = Request::param('ids');
                if(empty($ids)){
                    $code = 10001;
                    throw new Exception('缺少参数');
                }
                //批量删除--软删除
                $delete_count = $this->model
                    ->where([
                        ['id','in',$ids]
                    ])->update(['is_del'=>1]);

                if($delete_count > 0){
                    $msg = '操作成功';
                }else{
                    $code = 10002;
                    throw new Exception('删除失败');
                }

            }else{
                $code = 10001;
                throw new Exception('请求失败');
            }
        }catch (Exception $e){
            $code = 500;
            $msg = $e->getMessage();
        }

        return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);

    }


    /**
     * 编辑商家服务项目
     */
    public function srvItem(){

        $mchId = Request::get('id');
        $where1 = ['id'=>$mchId ];
        $merchant = $this->model->where($where1)->find();
        if(empty($merchant)){
            //不要跳转
            $this->error('商家不存在', null, null, 86400*100);
        }else{
            if($merchant['is_del']){
                $this->error('商家已被删除', null, null, 86400*100);
            }
        }

        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $item_ids = $this->request->post('item_ids/a', []);


            $data = null;
            Db::startTrans();
            try{
                MerchantServiceModel::where(['mch_id'=>$mchId])->delete();

                //批量添加
                $data = [];
                foreach ($item_ids as $id){
                    $data[] = [
                        'mch_id' => $mchId,
                        'srv_item_id' => $id,
                    ];
                }
                $ms = new MerchantServiceModel();
                $ms->saveAll($data);


                Db::commit();
                $msg = "保存成功";

            }catch (Exception $e){
                Db::rollback();
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }


        $this->assign('merchant', $merchant);

        $where2 = ['t1.status'=>1, ];   //可用服务
        $si = model('ServiceItem');
        $items = $si->alias('t1')
            ->field('t1.id,t1.service_name, t2.mch_id,t2.srv_item_id')
            ->leftJoin('merchant_service t2', 't2.mch_id='. $mchId .' AND t1.id=t2.srv_item_id')
            ->where($where2)
            ->select();
        $this->assign('items', $items);
        return $this->fetch();
    }


    /**
     * 编辑商家覆盖范围
     */
    public function overarea(){

        $mchId = Request::get('id');
        $where1 = ['id'=>$mchId ];
        $merchant = $this->model->where($where1)->find();
        if(empty($merchant)){
            //不要跳转
            $this->error('商家不存在', null, null, 86400*100);
        }else{
            if($merchant['is_del']){
                $this->error('商家已被删除', null, null, 86400*100);
            }
        }

        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $provinces = $this->request->post('srv_province/a', []);
            $citys = $this->request->post('srv_city/a', []);
            $areas = $this->request->post('srv_area/a', []);


            $data = null;
            Db::startTrans();
            try{
                MerchantOverareaModel::where(['mch_id'=>$mchId])->delete();

                //批量添加
                $data = [];
                foreach ($provinces as $idx=>$province){
                    if( empty($citys[$idx]) ){  //直辖市
                        $citys[$idx] = $province;
                    }
                    if( empty($areas[$citys[$idx]]) )   continue;   //未选择地区

                    $data[] = [
                        'mch_id' => $mchId,
                        'srv_province' => $province,
                        'srv_city' => $citys[$idx],
                        'srv_areas' => da_jencode( $areas[$citys[$idx]] ),  //json序列化
                    ];
                }
                $ms = new MerchantOverareaModel();
                $ms->saveAll($data);


                Db::commit();
                $msg = "保存成功";

            }catch (Exception $e){
                Db::rollback();
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>[],'msg'=>$msg,'code'=>$code]);
        }

        $this->assign('merchant', $merchant);

        $overarea = MerchantOverareaModel::where(['mch_id'=>$mchId])->select()->toArray();

        if($overarea){  //编辑
            foreach($overarea as &$val){
                if( mb_substr($val['srv_province'],-1,null, 'utf-8')=='市' ) $val['srv_city'] = '';  //直辖市
                $val['srv_areas'] = (array)(da_jdecode($val['srv_areas'], true));
            }
            unset($val);
            $this->assign('overarea', $overarea);


            return $this->fetch('overarea_edit');
        }else{
            //新增
            return $this->fetch();
        }
    }

}
